home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1992 June: ROMin Holiday / ADC Developer CD (1992-06) (''ROMin Holiday'')_iso / Developer Connection - 06-1992.iso / Periodicals / develop / develop 7 code / Futures / TESample.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-10-10  |  56.3 KB  |  1,758 lines  |  [TEXT/MPS ]

  1. /*------------------------------------------------------------------------------
  2. #
  3. #    Apple Macintosh Developer Technical Support
  4. #
  5. #    MultiFinder-Aware Simple TextEdit Sample Application
  6. #
  7. #    TESample
  8. #
  9. #    This file: TESample.c    -    C Source
  10. #
  11. #    Copyright © Apple Computer, Inc. 1989-1990
  12. #    All rights reserved.
  13. #
  14. #    Versions:    
  15. #                1.00                08/88
  16. #                1.01                11/88
  17. #                1.02                04/89    MPW 3.1
  18. #                1.03                02/90    MPW 3.2
  19. #
  20. #    Components:
  21. #                TESample.p            Feb.  1, 1990
  22. #                TESample.c            Feb.  1, 1990
  23. #                TESampleGlue.a        Feb.  1, 1990
  24. #                TESample.r            Feb.  1, 1990
  25. #                TESample.h            Feb.  1, 1990
  26. #                [P]TESample.make    Feb.  1, 1990
  27. #                [C]TESample.make    Feb.  1, 1990
  28. #
  29. #    TESample is an example application that demonstrates how 
  30. #    to initialize the commonly used toolbox managers, operate 
  31. #    successfully under MultiFinder, handle desk accessories and 
  32. #    create, grow, and zoom windows. The fundamental TextEdit 
  33. #    toolbox calls and TextEdit autoscroll are demonstrated. It 
  34. #    also shows how to create and maintain scrollbar controls.
  35. #
  36. #    It does not by any means demonstrate all the techniques you 
  37. #    need for a large application. In particular, Sample does not 
  38. #    cover exception handling, multiple windows/documents, 
  39. #    sophisticated memory management, printing, or undo. All of 
  40. #    these are vital parts of a normal full-sized application.
  41. #
  42. #    This application is an example of the form of a Macintosh 
  43. #    application; it is NOT a template. It is NOT intended to be 
  44. #    used as a foundation for the next world-class, best-selling, 
  45. #    600K application. A stick figure drawing of the human body may 
  46. #    be a good example of the form for a painting, but that does not 
  47. #    mean it should be used as the basis for the next Mona Lisa.
  48. #
  49. #    We recommend that you review this program or Sample before 
  50. #    beginning a new application. Sample is a simple app. which doesn’t 
  51. #    use TextEdit or the Control Manager.
  52. #
  53. ------------------------------------------------------------------------------*/
  54.  
  55.  
  56. /* Segmentation strategy:
  57.  
  58.    This program consists of three segments. Main contains most of the code,
  59.    including the MPW libraries, and the main program. Initialize contains
  60.    code that is only used once, during startup, and can be unloaded after the
  61.    program starts. %A5Init is automatically created by the Linker to initialize
  62.    globals for the MPW libraries and is unloaded right away. */
  63.  
  64.  
  65. /* SetPort strategy:
  66.  
  67.    Toolbox routines do not change the current port. In spite of this, in this
  68.    program we use a strategy of calling SetPort whenever we want to draw or
  69.    make calls which depend on the current port. This makes us less vulnerable
  70.    to bugs in other software which might alter the current port (such as the
  71.    bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  72.    Hopefully, this also makes the routines from this program more self-contained,
  73.    since they don't depend on the current port setting. */
  74.  
  75.  
  76. /* Clipboard strategy:
  77.  
  78.    This program does not maintain a private scrap. Whenever a cut, copy, or paste
  79.    occurs, we import/export from the public scrap to TextEdit's scrap right away,
  80.    using the TEToScrap and TEFromScrap routines. If we did use a private scrap,
  81.    the import/export would be in the activate/deactivate event and suspend/resume
  82.    event routines. */
  83.  
  84. /* A/UX is case sensitive, so use correct case for include file names */
  85. #include <values.h>
  86. #include <types.h>
  87. #include <quickdraw.h>
  88. #include <fonts.h>
  89. #include <events.h>
  90. #include <controls.h>
  91. #include <windows.h>
  92. #include <menus.h>
  93. #include <textedit.h>
  94. #include <dialogs.h>
  95. #include <desk.h>
  96. #include <scrap.h>
  97. #include <toolutils.h>
  98. #include <memory.h>
  99. #include <segload.h>
  100. #include <files.h>
  101. #include <osutils.h>
  102. #include <osevents.h>
  103. #include <diskinit.h>
  104. #include <packages.h>
  105. #include <traps.h>
  106. #include <string.h>
  107. #include "TESample.h"        /* bring in all the #defines for TESample */
  108.  
  109. /* A DocumentRecord contains the WindowRecord for one of our document windows,
  110.    as well as the TEHandle for the text we are editing. Other document fields
  111.    can be added to this record as needed. For a similar example, see how the
  112.    Window Manager and Dialog Manager add fields after the GrafPort. */
  113. typedef struct {
  114.     WindowRecord    docWindow;
  115.     TEHandle        docTE;
  116.     ControlHandle    docVScroll;
  117.     ControlHandle    docHScroll;
  118.     ProcPtr            docClik;
  119. } DocumentRecord, *DocumentPeek;
  120.  
  121.  
  122.  
  123. /* The "g" prefix is used to emphasize that a variable is global. */
  124.  
  125. /* GMac is used to hold the result of a SysEnvirons call. This makes
  126.    it convenient for any routine to check the environment. It is
  127.    global information, anyway. */
  128. SysEnvRec    gMac;                /* set up by Initialize */
  129.  
  130. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  131.    trap is available. If it is false, we know that we must call GetNextEvent. */
  132. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  133.  
  134. /* GInBackground is maintained by our OSEvent handling routines. Any part of
  135.    the program can check it to find out if it is currently in the background. */
  136. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  137.  
  138. /* GNumDocuments is used to keep track of how many open documents there are
  139.    at any time. It is maintained by the routines that open and close documents. */
  140. short        gNumDocuments;        /* maintained by Initialize, DoNew, and DoCloseWindow */
  141.  
  142.  
  143. /* Here are declarations for all of the C routines. In MPW 3.0 we can use
  144.    actual prototypes for parameter type checking. A/UX C does not grok
  145.    prototypes, so eliminate them under A/UX */
  146.     void AlertUser( short error );
  147.     void EventLoop( void );
  148.     void DoEvent( EventRecord *event );
  149.     void AdjustCursor( Point mouse, RgnHandle region );
  150.     void GetGlobalMouse( Point *mouse );
  151.     void DoGrowWindow( WindowPtr window, EventRecord *event );
  152.     void DoZoomWindow( WindowPtr window, short part );
  153.     void ResizeWindow( WindowPtr window );
  154.     void GetLocalUpdateRgn( WindowPtr window, RgnHandle localRgn );
  155.     void DoUpdate( WindowPtr window );
  156.     void DoDeactivate( WindowPtr window );
  157.     void DoActivate( WindowPtr window, Boolean becomingActive );
  158.     void DoContentClick( WindowPtr window, EventRecord *event );
  159.     void DoKeyDown( EventRecord *event );
  160.     unsigned long GetSleep( void );
  161.     void CommonAction( ControlHandle control, short *amount );
  162.     pascal void VActionProc( ControlHandle control, short part );
  163.     pascal void HActionProc( ControlHandle control, short part );
  164.     void DoIdle( void );
  165.     void DrawWindow( WindowPtr window );
  166.     void AdjustMenus( void );
  167.     void DoMenuCommand( long menuResult );
  168.     void DoNew( void );
  169.     Boolean DoCloseWindow( WindowPtr window );
  170.     void Terminate( void );
  171.     void Initialize( void );
  172.     void BigBadError( short error );
  173.     void GetTERect( WindowPtr window, Rect *teRect );
  174.     void AdjustViewRect( TEHandle docTE );
  175.     void AdjustTE( WindowPtr window );
  176.     void AdjustHV( Boolean isVert, ControlHandle control, TEHandle docTE,
  177.                     Boolean canRedraw );
  178.     void AdjustScrollValues( WindowPtr window, Boolean canRedraw );
  179.     void AdjustScrollSizes( WindowPtr window );
  180.     void AdjustScrollbars( WindowPtr window, Boolean needsResize );
  181.     pascal void PascalClikLoop();
  182.     pascal ProcPtr GetOldClikLoop();
  183.     Boolean IsAppWindow( WindowPtr window );
  184.     Boolean IsDAWindow( WindowPtr window );
  185.     Boolean TrapAvailable( short tNumber, TrapType tType );
  186.  
  187.  
  188. /* Define HiWrd and LoWrd macros for efficiency. */
  189. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  190. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  191.  
  192. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  193.    dependency on the ordering of fields within a Rect */
  194. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  195. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  196.  
  197. /* This routine is part of the MPW runtime library. This external
  198.    reference to it is done so that we can unload its segment, %A5Init. */
  199.  
  200. extern void _DataInit();
  201.  
  202.  
  203. /* A reference to our assembly language routine that gets attached to the clikLoop
  204. field of our TE record. */
  205.  
  206. extern pascal void AsmClikLoop();
  207.  
  208. /* ••• The following was added by MLG to demonstrate futures. ••••••••••••••••••••••••••••••••••••••••••••••••••• */
  209.  
  210. #include <PPCToolBox.h>
  211. #include <EPPC.h>
  212. #include <AppleEvents.h>
  213. #include "Futures.h"
  214. #include "Threads.h"
  215.  
  216. #define kSillyEventClass 'sily'
  217. #define kPingEvent 'ping'
  218.  
  219. #pragma segment handlers
  220. pascal OSErr HandlePing(AppleEvent question, AppleEvent answer, long handlerRefcon)
  221. {
  222.     char*            stringPtr;
  223.     char            stringBuffer[100];
  224.     long            actualSize;
  225.     DescType        actualType;
  226.     OSErr            theErr;
  227.  
  228. // Beep to indicate that the question was received
  229.  
  230.     SysBeep(120);
  231.  
  232. // Extract a string from the question.
  233.  
  234.     theErr = AEGetParamPtr(&question, 'qstr', 'TEXT', &actualType, (Ptr) &stringBuffer, sizeof(stringBuffer)-1, &actualSize);
  235.  
  236. // Load a string into the answer.
  237.  
  238.     stringPtr = &"I’m just fine.";
  239.     theErr = AEPutParamPtr(&answer, 'rstr', 'TEXT', stringPtr, strlen(stringPtr));
  240.  
  241.     return(noErr);
  242. }
  243.  
  244. /* •••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••• */
  245.  
  246.  
  247.  
  248. #pragma segment Main
  249. main()
  250. {
  251.     UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  252.     
  253.     /* 1.01 - call to ForceEnvirons removed */
  254.     
  255.     /*    If you have stack requirements that differ from the default,
  256.         then you could use SetApplLimit to increase StackSpace at 
  257.         this point, before calling MaxApplZone. */
  258.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  259.  
  260.     Initialize();                    /* initialize the program */
  261.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  262.  
  263. /* ••• The following was added by MLG to demonstrate futures. ••••••••••••••••••••••••••••••••••••••••••••••••••• */
  264.  
  265. // Initialize the threads package
  266.  
  267.     InitThreads(false);
  268.  
  269. // Initialize the futures package
  270.  
  271.     InitFutures();
  272.  
  273. // Install a handler for the ping messages in AppleEvents, so that when we receive these events, this routine will be called
  274.  
  275.     AEInstallEventHandler(kSillyEventClass, kPingEvent, (EventHandlerProcPtr) &HandlePing, 0, false);
  276.  
  277. /* •••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••• */
  278.  
  279.     EventLoop();                    /* call the main event loop */
  280. }
  281.  
  282.  
  283. /* Get events forever, and handle them by calling DoEvent.
  284.    Also call AdjustCursor each time through the loop. */
  285.  
  286. #pragma segment Main
  287. void EventLoop()
  288. {
  289.     RgnHandle    cursorRgn;
  290.     Boolean        gotEvent;
  291.     EventRecord    event;
  292.     Point        mouse;
  293.  
  294.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  295.     do {
  296.         /* use WNE if it is available */
  297.         if ( gHasWaitNextEvent ) {
  298.             GetGlobalMouse(&mouse);
  299.             AdjustCursor(mouse, cursorRgn);
  300.             gotEvent = WaitNextEvent(everyEvent, &event, GetSleep(), cursorRgn);
  301.         }
  302.         else {
  303.             SystemTask();
  304.             gotEvent = GetNextEvent(everyEvent, &event);
  305.         }
  306.         if ( gotEvent ) {
  307.             /* make sure we have the right cursor before handling the event */
  308.             AdjustCursor(event.where, cursorRgn);
  309.             DoEvent(&event);
  310.         } else DoIdle();
  311.         /*    If you are using modeless dialogs that have editText items,
  312.             you will want to call IsDialogEvent to give the caret a chance
  313.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  314.             for a non-NIL value before calling IsDialogEvent. */
  315. /* ••• The following was added by MLG to demonstrate futures. ••••••••••••••••••••••••••••••••••••••••••••••••••• */
  316.  
  317. // Yield control to other threads
  318.  
  319.         Yield();
  320.  
  321. /* •••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••• */
  322.     } while ( true );    /* loop forever; we quit via ExitToShell */
  323. } /*EventLoop*/
  324.  
  325.  
  326. /* Do the right thing for an event. Determine what kind of event it is, and call
  327.  the appropriate routines. */
  328.  
  329.  
  330. #pragma segment Main
  331. void DoEvent(event)
  332.     EventRecord    *event;
  333. {
  334.     short        part, err;
  335.     WindowPtr    window;
  336.     char        key;
  337.     Point        aPoint;
  338.  
  339.     switch ( event->what ) {
  340.  
  341. /* ••• The following was added by MLG to demonstrate futures. ••••••••••••••••••••••••••••••••••••••••••••••••••• */
  342.  
  343.         case kHighLevelEvent:
  344.             AEProcessAppleEvent(event);
  345.             break;
  346.  
  347. /* •••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••• */
  348.  
  349.         case nullEvent:
  350.             /* we idle for null/mouse moved events ands for events which aren’t
  351.                 ours (see EventLoop) */
  352.             DoIdle();
  353.             break;
  354.         case mouseDown:
  355.             part = FindWindow(event->where, &window);
  356.             switch ( part ) {
  357.                 case inMenuBar:             /* process a mouse menu command (if any) */
  358.                     AdjustMenus();    /* bring ’em up-to-date */
  359.                     DoMenuCommand(MenuSelect(event->where));
  360.                     break;
  361.                 case inSysWindow:           /* let the system handle the mouseDown */
  362.                     SystemClick(event, window);
  363.                     break;
  364.                 case inContent:
  365.                     if ( window != FrontWindow() ) {
  366.                         SelectWindow(window);
  367.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  368.                     } else
  369.                         DoContentClick(window, event);
  370.                     break;
  371.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  372.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  373.                     break;
  374.                 case inGoAway:
  375.                     if ( TrackGoAway(window, event->where) )
  376.                         DoCloseWindow(window); /* we don’t care if the user cancelled */
  377.                     break;
  378.                 case inGrow:
  379.                     DoGrowWindow(window, event);
  380.                     break;
  381.                 case inZoomIn:
  382.                 case inZoomOut:
  383.                 if ( TrackBox(window, event->where, part) )
  384.                         DoZoomWindow(window, part);
  385.                     break;
  386.             }
  387.             break;
  388.         case keyDown:
  389.         case autoKey:                       /* check for menukey equivalents */
  390.             key = event->message & charCodeMask;
  391.             if ( event->modifiers & cmdKey ) {    /* Command key down */
  392.                 if ( event->what == keyDown ) {
  393.                     AdjustMenus();            /* enable/disable/check menu items properly */
  394.                     DoMenuCommand(MenuKey(key));
  395.                 }
  396.             } else
  397.                 DoKeyDown(event);
  398.             break;
  399.         case activateEvt:
  400.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  401.             break;
  402.         case updateEvt:
  403.             DoUpdate((WindowPtr) event->message);
  404.             break;
  405.         /*    1.01 - It is not a bad idea to at least call DIBadMount in response
  406.             to a diskEvt, so that the user can format a floppy. */
  407.         case diskEvt:
  408.             if ( HiWord(event->message) != noErr ) {
  409.                 SetPt(&aPoint, kDILeft, kDITop);
  410.                 err = DIBadMount(aPoint, event->message);
  411.             }
  412.             break;
  413.         case kOSEvent:
  414.         /*    1.02 - must BitAND with 0x0FF to get only low byte */
  415.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  416.                 case kMouseMovedMessage:
  417.                     DoIdle();                    /* mouse-moved is also an idle event */
  418.                     break;
  419.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  420.                     gInBackground = (event->message & kResumeMask) == 0;
  421.                     DoActivate(FrontWindow(), !gInBackground);
  422.                     break;
  423.             }
  424.             break;
  425.     }
  426. } /*DoEvent*/
  427.  
  428.  
  429. /*    Change the cursor's shape, depending on its position. This also calculates the region
  430.     where the current cursor resides (for WaitNextEvent). When the mouse moves outside of
  431.     this region, an event is generated. If there is more to the event than just
  432.     “the mouse moved”, we get called before the event is processed to make sure
  433.     the cursor is the right one. In any (ahem) event, this is called again before we
  434.     fall back into WNE. */
  435.  
  436. #pragma segment Main
  437. void AdjustCursor(mouse,region)
  438.     Point        mouse;
  439.     RgnHandle    region;
  440. {
  441.     WindowPtr    window;
  442.     RgnHandle    arrowRgn;
  443.     RgnHandle    iBeamRgn;
  444.     Rect        iBeamRect;
  445.  
  446.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  447.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  448.         /* calculate regions for different cursor shapes */
  449.         arrowRgn = NewRgn();
  450.         iBeamRgn = NewRgn();
  451.  
  452.         /* start arrowRgn wide open */
  453.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  454.  
  455.         /* calculate iBeamRgn */
  456.         if ( IsAppWindow(window) ) {
  457.             iBeamRect = (*((DocumentPeek) window)->docTE)->viewRect;
  458.             SetPort(window);    /* make a global version of the viewRect */
  459.             LocalToGlobal(&TopLeft(iBeamRect));
  460.             LocalToGlobal(&BotRight(iBeamRect));
  461.             RectRgn(iBeamRgn, &iBeamRect);
  462.             /* we temporarily change the port’s origin to “globalfy” the visRgn */
  463.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  464.             SectRgn(iBeamRgn, window->visRgn, iBeamRgn);
  465.             SetOrigin(0, 0);
  466.         }
  467.  
  468.         /* subtract other regions from arrowRgn */
  469.         DiffRgn(arrowRgn, iBeamRgn, arrowRgn);
  470.  
  471.         /* change the cursor and the region parameter */
  472.         if ( PtInRgn(mouse, iBeamRgn) ) {
  473.             SetCursor(*GetCursor(iBeamCursor));
  474.             CopyRgn(iBeamRgn, region);
  475.         } else {
  476.             SetCursor(&qd.arrow);
  477.             CopyRgn(arrowRgn, region);
  478.         }
  479.  
  480.         DisposeRgn(arrowRgn);
  481.         DisposeRgn(iBeamRgn);
  482.     }
  483. } /*AdjustCursor*/
  484.  
  485.  
  486. /*    Get the global coordinates of the mouse. When you call OSEventAvail
  487.     it will return either a pending event or a null event. In either case,
  488.     the where field of the event record will contain the current position
  489.     of the mouse in global coordinates and the modifiers field will reflect
  490.     the current state of the modifiers. Another way to get the global
  491.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  492.     being sure that thePort is set to a valid port. */
  493.  
  494. #pragma segment Main
  495. void GetGlobalMouse(mouse)
  496.     Point    *mouse;
  497. {
  498.     EventRecord    event;
  499.     
  500.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  501.     *mouse = event.where;                /* just the mouse position */
  502. } /*GetGlobalMouse*/
  503.  
  504.  
  505. /*    Called when a mouseDown occurs in the grow box of an active window. In
  506.     order to eliminate any 'flicker', we want to invalidate only what is
  507.     necessary. Since ResizeWindow invalidates the whole portRect, we save
  508.     the old TE viewRect, intersect it with the new TE viewRect, and
  509.     remove the result from the update region. However, we must make sure
  510.     that any old update region that might have been around gets put back. */
  511.  
  512. #pragma segment Main
  513. void DoGrowWindow(window,event)
  514.     WindowPtr    window;
  515.     EventRecord    *event;
  516. {
  517.     long        growResult;
  518.     Rect        tempRect;
  519.     RgnHandle    tempRgn;
  520.     DocumentPeek doc;
  521.     
  522.     tempRect = qd.screenBits.bounds;                    /* set up limiting values */
  523.     tempRect.left = kMinDocDim;
  524.     tempRect.top = kMinDocDim;
  525.     growResult = GrowWindow(window, event->where, &tempRect);
  526.     /* see if it really changed size */
  527.     if ( growResult != 0 ) {
  528.         doc = (DocumentPeek) window;
  529.         tempRect = (*doc->docTE)->viewRect;                /* save old text box */
  530.         tempRgn = NewRgn();
  531.         GetLocalUpdateRgn(window, tempRgn);                /* get localized update region */
  532.         SizeWindow(window, LoWrd(growResult), HiWrd(growResult), true);
  533.         ResizeWindow(window);
  534.         /* calculate & validate the region that hasn’t changed so it won’t get redrawn */
  535.         SectRect(&tempRect, &(*doc->docTE)->viewRect, &tempRect);
  536.         ValidRect(&tempRect);                            /* take it out of update */
  537.         InvalRgn(tempRgn);                                /* put back any prior update */
  538.         DisposeRgn(tempRgn);
  539.     }
  540. } /* DoGrowWindow */
  541.  
  542.  
  543. /*     Called when a mouseClick occurs in the zoom box of an active window.
  544.     Everything has to get re-drawn here, so we don't mind that
  545.     ResizeWindow invalidates the whole portRect. */
  546.  
  547. #pragma segment Main
  548. void DoZoomWindow(window,part)
  549.     WindowPtr    window;
  550.     short        part;
  551. {
  552.     EraseRect(&window->portRect);
  553.     ZoomWindow(window, part, window == FrontWindow());
  554.     ResizeWindow(window);
  555. } /*  DoZoomWindow */
  556.  
  557.  
  558. /* Called when the window has been resized to fix up the controls and content. */
  559. #pragma segment Main
  560. void ResizeWindow(window)
  561.     WindowPtr    window;
  562. {
  563.     AdjustScrollbars(window, true);
  564.     AdjustTE(window);
  565.     InvalRect(&window->portRect);
  566. } /* ResizeWindow */
  567.  
  568.  
  569. /* Returns the update region in local coordinates */
  570. #pragma segment Main
  571. void GetLocalUpdateRgn(window,localRgn)
  572.     WindowPtr    window;
  573.     RgnHandle    localRgn;
  574. {
  575.     CopyRgn(((WindowPeek) window)->updateRgn, localRgn);    /* save old update region */
  576.     OffsetRgn(localRgn, window->portBits.bounds.left, window->portBits.bounds.top);
  577. } /* GetLocalUpdateRgn */
  578.  
  579.  
  580. /*    This is called when an update event is received for a window.
  581.     It calls DrawWindow to draw the contents of an application window.
  582.     As an efficiency measure that does not have to be followed, it
  583.     calls the drawing routine only if the visRgn is non-empty. This
  584.     will handle situations where calculations for drawing or drawing
  585.     itself is very time-consuming. */
  586.  
  587. #pragma segment Main
  588. void DoUpdate(window)
  589.     WindowPtr    window;
  590. {
  591.     if ( IsAppWindow(window) ) {
  592.         BeginUpdate(window);                /* this sets up the visRgn */
  593.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  594.             DrawWindow(window);
  595.         EndUpdate(window);
  596.     }
  597. } /*DoUpdate*/
  598.  
  599.  
  600. /*    This is called when a window is activated or deactivated.
  601.     It calls TextEdit to deal with the selection. */
  602.  
  603. #pragma segment Main
  604. void DoActivate(window, becomingActive)
  605.     WindowPtr    window;
  606.     Boolean        becomingActive;
  607. {
  608.     RgnHandle    tempRgn, clipRgn;
  609.     Rect        growRect;
  610.     DocumentPeek doc;
  611.     
  612.     if ( IsAppWindow(window) ) {
  613.         doc = (DocumentPeek) window;
  614.         if ( becomingActive ) {
  615.             /*    since we don’t want TEActivate to draw a selection in an area where
  616.                 we’re going to erase and redraw, we’ll clip out the update region
  617.                 before calling it. */
  618.             tempRgn = NewRgn();
  619.             clipRgn = NewRgn();
  620.             GetLocalUpdateRgn(window, tempRgn);            /* get localized update region */
  621.             GetClip(clipRgn);
  622.             DiffRgn(clipRgn, tempRgn, tempRgn);            /* subtract updateRgn from clipRgn */
  623.             SetClip(tempRgn);
  624.             TEActivate(doc->docTE);
  625.             SetClip(clipRgn);                            /* restore the full-blown clipRgn */
  626.             DisposeRgn(tempRgn);
  627.             DisposeRgn(clipRgn);
  628.             
  629.             /* the controls must be redrawn on activation: */
  630.             (*doc->docVScroll)->contrlVis = kControlVisible;
  631.             (*doc->docHScroll)->contrlVis = kControlVisible;
  632.             InvalRect(&(*doc->docVScroll)->contrlRect);
  633.             InvalRect(&(*doc->docHScroll)->contrlRect);
  634.             /* the growbox needs to be redrawn on activation: */
  635.             growRect = window->portRect;
  636.             /* adjust for the scrollbars */
  637.             growRect.top = growRect.bottom - kScrollbarAdjust;
  638.             growRect.left = growRect.right - kScrollbarAdjust;
  639.             InvalRect(&growRect);
  640.         }
  641.         else {        
  642.             TEDeactivate(doc->docTE);
  643.             /* the controls must be hidden on deactivation: */
  644.             HideControl(doc->docVScroll);
  645.             HideControl(doc->docHScroll);
  646.             /* the growbox should be changed immediately on deactivation: */
  647.             DrawGrowIcon(window);
  648.         }
  649.     }
  650. } /*DoActivate*/
  651.  
  652.  
  653. /*    This is called when a mouseDown occurs in the content of a window. */
  654.  
  655. #pragma segment Main
  656. void DoContentClick(window,event)
  657.     WindowPtr    window;
  658.     EventRecord    *event;
  659. {
  660.     Point        mouse;
  661.     ControlHandle control;
  662.     short        part, value;
  663.     Boolean        shiftDown;
  664.     DocumentPeek doc;
  665.     Rect        teRect;
  666.  
  667.     if ( IsAppWindow(window) ) {
  668.         SetPort(window);
  669.         mouse = event->where;                            /* get the click position */
  670.         GlobalToLocal(&mouse);
  671.         doc = (DocumentPeek) window;
  672.         /* see if we are in the viewRect. if so, we won’t check the controls */
  673.         GetTERect(window, &teRect);
  674.         if ( PtInRect(mouse, &teRect) ) {
  675.             /* see if we need to extend the selection */
  676.             shiftDown = (event->modifiers & shiftKey) != 0;    /* extend if Shift is down */
  677.             TEClick(mouse, shiftDown, doc->docTE);
  678.         } else {
  679.             part = FindControl(mouse, window, &control);
  680.             switch ( part ) {
  681.                 case 0:                            /* do nothing for viewRect case */
  682.                     break;
  683.                 case inThumb:
  684.                     value = GetCtlValue(control);
  685.                     part = TrackControl(control, mouse, nil);
  686.                     if ( part != 0 ) {
  687.                         value -= GetCtlValue(control);
  688.                         /* value now has CHANGE in value; if value changed, scroll */
  689.                         if ( value != 0 )
  690.                             if ( control == doc->docVScroll )
  691.                                 TEScroll(0, value * (*doc->docTE)->lineHeight, doc->docTE);
  692.                             else
  693.                                 TEScroll(value, 0, doc->docTE);
  694.                     }
  695.                     break;
  696.                 default:                        /* they clicked in an arrow, so track & scroll */
  697.                     if ( control == doc->docVScroll )
  698.                         value = TrackControl(control, mouse, (ProcPtr) VActionProc);
  699.                     else
  700.                         value = TrackControl(control, mouse, (ProcPtr) HActionProc);
  701.                     break;
  702.             }
  703.         }
  704.     }
  705. } /*DoContentClick*/
  706.  
  707.  
  708. /* This is called for any keyDown or autoKey events, except when the
  709.  Command key is held down. It looks at the frontmost window to decide what
  710.  to do with the key typed. */
  711.  
  712. #pragma segment Main
  713. void DoKeyDown(event)
  714.     EventRecord    *event;
  715. {
  716.     WindowPtr    window;
  717.     char        key;
  718.     TEHandle    te;
  719.  
  720.     window = FrontWindow();
  721.     if ( IsAppWindow(window) ) {
  722.         te = ((DocumentPeek) window)->docTE;
  723.         key = event->message & charCodeMask;
  724.         /* we have a char. for our window; see if we are still below TextEdit’s
  725.             limit for the number of characters (but deletes are always rad) */
  726.         if ( key == kDelChar ||
  727.                 (*te)->teLength - ((*te)->selEnd - (*te)->selStart) + 1 <
  728.                 kMaxTELength ) {
  729.             TEKey(key, te);
  730.             AdjustScrollbars(window, false);
  731.             AdjustTE(window);
  732.         } else
  733.             AlertUser(eExceedChar);
  734.     }
  735. } /*DoKeyDown*/
  736.  
  737.  
  738. /* ••• The following was modified by MLG to demonstrate futures. ••••••••••••••••••••••••••••••••••••••••••••••••••• */
  739.  
  740. /*    Calculate a sleep value for WaitNextEvent. */
  741.  
  742. #pragma segment Main
  743. unsigned long GetSleep()
  744. {
  745.     long        sleep;
  746.  
  747.     sleep = 1;        // Sleep for the minimum sleep time of one tick.    I would prefer “yield” semantics however.
  748.     return sleep;
  749. } /*GetSleep*/
  750. /* •••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••• */
  751.  
  752.  
  753. /*    Common algorithm for pinning the value of a control. It returns the actual amount
  754.     the value of the control changed. Note the pinning is done for the sake of returning
  755.     the amount the control value changed. */
  756.  
  757. #pragma segment Main
  758. void CommonAction(control,amount)
  759.     ControlHandle control;
  760.     short        *amount;
  761. {
  762.     short        value, max;
  763.     
  764.     value = GetCtlValue(control);    /* get current value */
  765.     max = GetCtlMax(control);        /* and maximum value */
  766.     *amount = value - *amount;
  767.     if ( *amount < 0 )
  768.         *amount = 0;
  769.     else if ( *amount > max )
  770.         *amount = max;
  771.     SetCtlValue(control, *amount);
  772.     *amount = value - *amount;        /* calculate the real change */
  773. } /* CommonAction */
  774.  
  775.  
  776. /* Determines how much to change the value of the vertical scrollbar by and how
  777.     much to scroll the TE record. */
  778.  
  779. #pragma segment Main
  780. pascal void VActionProc(control,part)
  781.     ControlHandle control;
  782.     short        part;
  783. {
  784.     short        amount;
  785.     WindowPtr    window;
  786.     TEPtr        te;
  787.     
  788.     if ( part != 0 ) {                /* if it was actually in the control */
  789.         window = (*control)->contrlOwner;
  790.         te = *((DocumentPeek) window)->docTE;
  791.         switch ( part ) {
  792.             case inUpButton:
  793.             case inDownButton:        /* one line */
  794.                 amount = 1;
  795.                 break;
  796.             case inPageUp:            /* one page */
  797.             case inPageDown:
  798.                 amount = (te->viewRect.bottom - te->viewRect.top) / te->lineHeight;
  799.                 break;
  800.         }
  801.         if ( (part == inDownButton) || (part == inPageDown) )
  802.             amount = -amount;        /* reverse direction for a downer */
  803.         CommonAction(control, &amount);
  804.         if ( amount != 0 )
  805.             TEScroll(0, amount * te->lineHeight, ((DocumentPeek) window)->docTE);
  806.     }
  807. } /* VActionProc */
  808.  
  809.  
  810. /* Determines how much to change the value of the horizontal scrollbar by and how
  811. much to scroll the TE record. */
  812.  
  813. #pragma segment Main
  814. pascal void HActionProc(control,part)
  815.     ControlHandle control;
  816.     short        part;
  817. {
  818.     short        amount;
  819.     WindowPtr    window;
  820.     TEPtr        te;
  821.     
  822.     if ( part != 0 ) {
  823.         window = (*control)->contrlOwner;
  824.         te = *((DocumentPeek) window)->docTE;
  825.         switch ( part ) {
  826.             case inUpButton:
  827.             case inDownButton:        /* a few pixels */
  828.                 amount = kButtonScroll;
  829.                 break;
  830.             case inPageUp:            /* a page */
  831.             case inPageDown:
  832.                 amount = te->viewRect.right - te->viewRect.left;
  833.                 break;
  834.         }
  835.         if ( (part == inDownButton) || (part == inPageDown) )
  836.             amount = -amount;        /* reverse direction */
  837.         CommonAction(control, &amount);
  838.         if ( amount != 0 )
  839.             TEScroll(amount, 0, ((DocumentPeek) window)->docTE);
  840.     }
  841. } /* VActionProc */
  842.  
  843.  
  844. /* This is called whenever we get a null event et al.
  845.  It takes care of necessary periodic actions. For this program, it calls TEIdle. */
  846.  
  847. #pragma segment Main
  848. void DoIdle()
  849. {
  850.     WindowPtr    window;
  851.  
  852.     window = FrontWindow();
  853.     if ( IsAppWindow(window) )
  854.         TEIdle(((DocumentPeek) window)->docTE);
  855.  
  856.  
  857. /* ••• The following was added by MLG to demonstrate futures. ••••••••••••••••••••••••••••••••••••••••••••••••••• */
  858.  
  859. // Yield control to other threads
  860.  
  861.         Yield();
  862.  
  863. /* •••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••• */
  864.  
  865.  
  866. } /*DoIdle*/
  867.  
  868.  
  869. /* Draw the contents of an application window. */
  870.  
  871. #pragma segment Main
  872. void DrawWindow(window)
  873.     WindowPtr    window;
  874. {
  875.     SetPort(window);
  876.     EraseRect(&window->portRect);
  877.     DrawControls(window);
  878.     DrawGrowIcon(window);
  879.     TEUpdate(&window->portRect, ((DocumentPeek) window)->docTE);
  880. } /*DrawWindow*/
  881.  
  882.  
  883. /*    Enable and disable menus based on the current state.
  884.     The user can only select enabled menu items. We set up all the menu items
  885.     before calling MenuSelect or MenuKey, since these are the only times that
  886.     a menu item can be selected. Note that MenuSelect is also the only time
  887.     the user will see menu items. This approach to deciding what enable/
  888.     disable state a menu item has the advantage of concentrating all
  889.     the decision-making in one routine, as opposed to being spread throughout
  890.     the application. Other application designs may take a different approach
  891.     that may or may not be as valid. */
  892.  
  893. #pragma segment Main
  894. void AdjustMenus()
  895. {
  896.     WindowPtr    window;
  897.     MenuHandle    menu;
  898.     long        offset;
  899.     Boolean        undo;
  900.     Boolean        cutCopyClear;
  901.     Boolean        paste;
  902.     TEHandle    te;
  903.  
  904.     window = FrontWindow();
  905.  
  906.     menu = GetMHandle(mFile);
  907.     if ( gNumDocuments < kMaxOpenDocuments )
  908.         EnableItem(menu, iNew);        /* New is enabled when we can open more documents */
  909.     else
  910.         DisableItem(menu, iNew);
  911.     if ( window != nil )            /* Close is enabled when there is a window to close */
  912.         EnableItem(menu, iClose);
  913.     else
  914.         DisableItem(menu, iClose);
  915.  
  916.     menu = GetMHandle(mEdit);
  917.     undo = false;
  918.     cutCopyClear = false;
  919.     paste = false;
  920.     if ( IsDAWindow(window) ) {
  921.         undo = true;                /* all editing is enabled for DA windows */
  922.         cutCopyClear = true;
  923.         paste = true;
  924.     } else if ( IsAppWindow(window) ) {
  925.         te = ((DocumentPeek) window)->docTE;
  926.         if ( (*te)->selStart < (*te)->selEnd )
  927.             cutCopyClear = true;
  928.             /* Cut, Copy, and Clear is enabled for app. windows with selections */
  929.         if ( GetScrap(nil, 'TEXT', &offset)  > 0)
  930.             paste = true;            /* if there’s any text in the clipboard, paste is enabled */
  931.     }
  932.     if ( undo )
  933.         EnableItem(menu, iUndo);
  934.     else
  935.         DisableItem(menu, iUndo);
  936.     if ( cutCopyClear ) {
  937.         EnableItem(menu, iCut);
  938.         EnableItem(menu, iCopy);
  939.         EnableItem(menu, iClear);
  940.     } else {
  941.         DisableItem(menu, iCut);
  942.         DisableItem(menu, iCopy);
  943.         DisableItem(menu, iClear);
  944.     }
  945.     if ( paste )
  946.         EnableItem(menu, iPaste);
  947.     else
  948.         DisableItem(menu, iPaste);
  949.         
  950.         
  951. /* ••• The following was added by MLG to demonstrate futures. ••••••••••••••••••••••••••••••••••••••••••••••••••• */
  952.  
  953.     menu = GetMHandle(mTest);
  954.     EnableItem(menu, iPing);
  955.     EnableItem(menu, iPing2);
  956.  
  957. /* •••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••• */
  958.         
  959.         
  960. } /*AdjustMenus*/
  961.  
  962.  
  963. /*    This is called when an item is chosen from the menu bar (after calling
  964.     MenuSelect or MenuKey). It does the right thing for each command. */
  965.  
  966. #pragma segment Main
  967. void DoMenuCommand(menuResult)
  968.     long        menuResult;
  969. {
  970.     short        menuID, menuItem;
  971.     short        itemHit, daRefNum;
  972.     Str255        daName;
  973.     OSErr        saveErr;
  974.     TEHandle    te;
  975.     WindowPtr    window;
  976.     Handle        aHandle;
  977.     long        oldSize, newSize;
  978.     long        total, contig;
  979.  
  980.     window = FrontWindow();
  981.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  982.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  983.     switch ( menuID ) {
  984.         case mApple:
  985.             switch ( menuItem ) {
  986.                 case iAbout:        /* bring up alert for About */
  987.                     itemHit = Alert(rAboutAlert, nil);
  988.                     break;
  989.                 default:            /* all non-About items in this menu are DAs et al */
  990.                     /* type Str255 is an array in MPW 3 */
  991.                     GetItem(GetMHandle(mApple), menuItem, daName);
  992.                     daRefNum = OpenDeskAcc(daName);
  993.                     break;
  994.             }
  995.             break;
  996.         case mFile:
  997.             switch ( menuItem ) {
  998.                 case iNew:
  999.                     DoNew();
  1000.                     break;
  1001.                 case iClose:
  1002.                     DoCloseWindow(FrontWindow());            /* ignore the result */
  1003.                     break;
  1004.                 case iQuit:
  1005.                     Terminate();
  1006.                     break;
  1007.             }
  1008.             break;
  1009.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  1010.             if ( !SystemEdit(menuItem-1) ) {
  1011.                 te = ((DocumentPeek) FrontWindow())->docTE;
  1012.                 switch ( menuItem ) {
  1013.                     case iCut:
  1014.                         if ( ZeroScrap() == noErr ) {
  1015.                             PurgeSpace(&total, &contig);
  1016.                             if ((*te)->selEnd - (*te)->selStart + kTESlop > contig)
  1017.                                 AlertUser(eNoSpaceCut);
  1018.                             else 
  1019.                                 {
  1020.                                 TECut(te);
  1021.                                 if ( TEToScrap() != noErr ) {
  1022.                                     AlertUser(eNoCut);
  1023.                                     ZeroScrap();
  1024.                                 }
  1025.                             }
  1026.                         }
  1027.                         break;
  1028.                     case iCopy:
  1029.                         if ( ZeroScrap() == noErr ) {
  1030.                             TECopy(te);    /* after copying, export the TE scrap */
  1031.                             if ( TEToScrap() != noErr ) {
  1032.                                 AlertUser(eNoCopy);
  1033.                                 ZeroScrap();
  1034.                             }
  1035.                         }
  1036.                         break;
  1037.                     case iPaste:    /* import the TE scrap before pasting */
  1038.                         if ( TEFromScrap() == noErr ) {
  1039.                             if ( TEGetScrapLen() + ((*te)->teLength -
  1040.                                 ((*te)->selEnd - (*te)->selStart)) > kMaxTELength )
  1041.                                 AlertUser(eExceedPaste);
  1042.                             else {
  1043.                                 aHandle = (Handle) TEGetText(te);
  1044.                                 oldSize = GetHandleSize(aHandle);
  1045.                                 newSize = oldSize + TEGetScrapLen() + kTESlop;
  1046.                                 SetHandleSize(aHandle, newSize);
  1047.                                 saveErr = MemError();
  1048.                                 SetHandleSize(aHandle, oldSize);
  1049.                                 if (saveErr != noErr)
  1050.                                     AlertUser(eNoSpacePaste);
  1051.                                 else
  1052.                                     TEPaste(te);
  1053.                             }
  1054.                         }
  1055.                         else
  1056.                             AlertUser(eNoPaste);
  1057.                         break;
  1058.                     case iClear:
  1059.                         TEDelete(te);
  1060.                         break;
  1061.                 }
  1062.             AdjustScrollbars(window, false);
  1063.             AdjustTE(window);
  1064.             }
  1065.             break;
  1066.  
  1067. /* ••• The following was added by MLG to demonstrate futures. ••••••••••••••••••••••••••••••••••••••••••••••••••• */
  1068.  
  1069.         case mTest:
  1070.             switch ( menuItem ) {
  1071.                 case iPing:
  1072.                     {
  1073.                     OSErr            theErr;
  1074.                     TargetID        theTargetID;
  1075.                     PortInfoRec        thePortInfo;
  1076.                     AEAddressDesc    theAddressDesc;
  1077.                     ThreadHandle    theThread;
  1078.                     AppleEvent        question;
  1079.                     AppleEvent        answer;
  1080.                     char*            stringPtr;
  1081.                     char            stringBuffer[100];
  1082.                     long            actualSize;
  1083.                     DescType        actualType;
  1084.  
  1085. // Get the target address of the other process
  1086.         
  1087.                     theErr = PPCBrowser("\p", "\p", false, &theTargetID.location, &thePortInfo, nil, "\p");
  1088.                     theTargetID.name = thePortInfo.name;
  1089.                     theErr = AECreateDesc(typeTargetID, (Ptr) &theTargetID, sizeof(TargetID), &theAddressDesc);
  1090.         
  1091. // Start the thread that pings
  1092.         
  1093.                     if (InNewThread(&theThread, kDefaultStackSize))
  1094.                         {
  1095.                         long i;
  1096.                         for (i=0; i<30; i++)
  1097.                             {
  1098.                             Yield();
  1099.         
  1100. // Build an AppleEvent question that is addressed to the user selected target
  1101.                     
  1102.                             theErr = AECreateAppleEvent(kSillyEventClass, kPingEvent, &theAddressDesc, kAutoGenerateReturnID, kAnyTransactionID, &question);
  1103.                             
  1104. // Load a string into the question.
  1105.  
  1106.                             stringPtr = &"Hello server, how are you doing?";
  1107.                             theErr = AEPutParamPtr(&question, 'qstr', 'TEXT', stringPtr, strlen(stringPtr));
  1108.  
  1109. // Ask the question
  1110.         
  1111.                             theErr = Ask(&question, &answer);
  1112.  
  1113. // If the answer is not a future so soon after ask, something is probably wrong.
  1114.  
  1115.                             // if (!IsFuture(&answer)) Debugger();
  1116.  
  1117. // Extract a string from the answer.  This will cause the thread to block until the answer is received.
  1118.  
  1119.                             theErr = AEGetParamPtr(&answer, 'rstr', 'TEXT', &actualType, (Ptr) &stringBuffer, sizeof(stringBuffer)-1, &actualSize);
  1120.  
  1121. // If the answer is still a future after retrieving a string from the answer, something is definitely wrong.
  1122.  
  1123.                             // if (IsFuture(&answer)) Debugger();
  1124.  
  1125. // Dispose of the answer and the question.
  1126.                             
  1127.                             theErr = AEDisposeDesc(&answer);
  1128.                             theErr = AEDisposeDesc(&question);
  1129.                             }
  1130.         
  1131. // Dispose of the address descriptor now that the thread no longer needs it.
  1132.         
  1133.                         theErr = AEDisposeDesc(&theAddressDesc);
  1134.                         EndThread(theThread);
  1135.                         }
  1136.                     }
  1137.                     break;
  1138.                 case iPing2:
  1139.                     {
  1140.                     OSErr            theErr;
  1141.                     TargetID        theTargetID;
  1142.                     PortInfoRec        thePortInfo;
  1143.                     AEAddressDesc    theAddressDesc;
  1144.                     AEAddressDesc    theAddressDesc2;
  1145.                     ThreadHandle    theThread;
  1146.                     AppleEvent        question;
  1147.                     AppleEvent        question2;
  1148.                     AppleEvent        answer;
  1149.                     AppleEvent        answer2;
  1150.     
  1151. // Get the target addresses of the two processes
  1152.         
  1153.                     theErr = PPCBrowser("\p", "\p", false, &theTargetID.location, &thePortInfo, nil, "\p");
  1154.                     theTargetID.name = thePortInfo.name;
  1155.                     theErr = AECreateDesc(typeTargetID, (Ptr) &theTargetID, sizeof(TargetID), &theAddressDesc);
  1156.         
  1157.                     theErr = PPCBrowser("\p", "\p", false, &theTargetID.location, &thePortInfo, nil, "\p");
  1158.                     theTargetID.name = thePortInfo.name;
  1159.                     theErr = AECreateDesc(typeTargetID, (Ptr) &theTargetID, sizeof(TargetID), &theAddressDesc2);
  1160.         
  1161. // Start the thread that pings
  1162.         
  1163.                     if (InNewThread(&theThread, kDefaultStackSize))
  1164.                         {
  1165.                         long i;
  1166.                         for (i=0; i<30; i++)
  1167.                             {
  1168.                             Yield();
  1169.         
  1170. // Build the questions.
  1171.                     
  1172.                             theErr = AECreateAppleEvent(kSillyEventClass, kPingEvent, &theAddressDesc, kAutoGenerateReturnID, kAnyTransactionID, &question);
  1173.                             theErr = AECreateAppleEvent(kSillyEventClass, kPingEvent, &theAddressDesc2, kAutoGenerateReturnID, kAnyTransactionID, &question2);
  1174.                             
  1175. // Ask the questions.
  1176.         
  1177.                             theErr = Ask(&question, &answer);
  1178.                             theErr = Ask(&question2, &answer2);
  1179.         
  1180. // Block until the answers become real.
  1181.  
  1182.                             theErr = BlockUntilReal(&answer);
  1183.                             theErr = BlockUntilReal(&answer2);
  1184.  
  1185. // Dispose of the answers and the questions.
  1186.  
  1187.                             theErr = AEDisposeDesc(&answer);
  1188.                             theErr = AEDisposeDesc(&answer2);
  1189.                             theErr = AEDisposeDesc(&question);
  1190.                             theErr = AEDisposeDesc(&question2);
  1191.                             }
  1192.         
  1193. // Dispose of the address descriptor now that the thread no longer needs it.
  1194.         
  1195.                         theErr = AEDisposeDesc(&theAddressDesc);
  1196.                         theErr = AEDisposeDesc(&theAddressDesc2);
  1197.                         EndThread(theThread);
  1198.                         }
  1199.                     }
  1200.                     break;
  1201.             }
  1202.             break;
  1203.  
  1204. /* •••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••• */
  1205.  
  1206.     }
  1207.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  1208. } /*DoMenuCommand*/
  1209.  
  1210.  
  1211. /* Create a new document and window. */
  1212.  
  1213. #pragma segment Main
  1214. void DoNew()
  1215. {
  1216.     Boolean        good;
  1217.     Ptr            storage;
  1218.     WindowPtr    window;
  1219.     Rect        destRect, viewRect;
  1220.     DocumentPeek doc;
  1221.  
  1222.     storage = NewPtr(sizeof(DocumentRecord));
  1223.     if ( storage != nil ) {
  1224.         window = GetNewWindow(rDocWindow, storage, (WindowPtr) -1);
  1225.         if ( window != nil ) {
  1226.             gNumDocuments += 1;            /* this will be decremented when we call DoCloseWindow */
  1227.             good = false;
  1228.             SetPort(window);
  1229.             doc =  (DocumentPeek) window;
  1230.             GetTERect(window, &viewRect);
  1231.             destRect = viewRect;
  1232.             destRect.right = destRect.left + kMaxDocWidth;
  1233.             doc->docTE = TENew(&destRect, &viewRect);
  1234.             good = doc->docTE != nil;    /* if TENew succeeded, we have a good document */
  1235.             if ( good ) {                /* 1.02 - good document? — proceed */
  1236.                 AdjustViewRect(doc->docTE);
  1237.                 TEAutoView(true, doc->docTE);
  1238.                 doc->docClik = (ProcPtr) (*doc->docTE)->clikLoop;
  1239.                 (*doc->docTE)->clikLoop = (ClikLoopProcPtr) AsmClikLoop;
  1240.             }
  1241.             
  1242.             if ( good ) {                /* good document? — get scrollbars */
  1243.                 doc->docVScroll = GetNewControl(rVScroll, window);
  1244.                 good = (doc->docVScroll != nil);
  1245.             }
  1246.             if ( good) {
  1247.                 doc->docHScroll = GetNewControl(rHScroll, window);
  1248.                 good = (doc->docHScroll != nil);
  1249.             }
  1250.             
  1251.             if ( good ) {                /* good? — adjust & draw the controls, draw the window */
  1252.                 /* false to AdjustScrollValues means musn’t redraw; technically, of course,
  1253.                 the window is hidden so it wouldn’t matter whether we called ShowControl or not. */
  1254.                 AdjustScrollValues(window, false);
  1255.                 ShowWindow(window);
  1256.             } else {
  1257.                 DoCloseWindow(window);    /* otherwise regret we ever created it... */
  1258.                 AlertUser(eNoWindow);            /* and tell user */
  1259.             }
  1260.         } else
  1261.             DisposPtr(storage);            /* get rid of the storage if it is never used */
  1262.     }
  1263. } /*DoNew*/
  1264.  
  1265.  
  1266. /* Close a window. This handles desk accessory and application windows. */
  1267.  
  1268. /*    1.01 - At this point, if there was a document associated with a
  1269.     window, you could do any document saving processing if it is 'dirty'.
  1270.     DoCloseWindow would return true if the window actually closed, i.e.,
  1271.     the user didn’t cancel from a save dialog. This result is handy when
  1272.     the user quits an application, but then cancels the save of a document
  1273.     associated with a window. */
  1274.  
  1275. #pragma segment Main
  1276. Boolean DoCloseWindow(window)
  1277.     WindowPtr    window;
  1278. {
  1279.     TEHandle    te;
  1280.  
  1281.     if ( IsDAWindow(window) )
  1282.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  1283.     else if ( IsAppWindow(window) ) {
  1284.         te = ((DocumentPeek) window)->docTE;
  1285.         if ( te != nil )
  1286.             TEDispose(te);            /* dispose the TEHandle if we got far enough to make one */
  1287.         /*    1.01 - We used to call DisposeWindow, but that was technically
  1288.             incorrect, even though we allocated storage for the window on
  1289.             the heap. We should instead call CloseWindow to have the structures
  1290.             taken care of and then dispose of the storage ourselves. */
  1291.         CloseWindow(window);
  1292.         DisposPtr((Ptr) window);
  1293.         gNumDocuments -= 1;
  1294.     }
  1295.     return true;
  1296. } /*DoCloseWindow*/
  1297.  
  1298.  
  1299. /**************************************************************************************
  1300. *** 1.01 DoCloseBehind(window) was removed ***
  1301.  
  1302.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  1303.     and not having to worry about updating the windows, but it suffered
  1304.     from a fatal flaw. If a desk accessory owned two windows, it would
  1305.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  1306.     got around to calling DoCloseWindow for that other window that was already
  1307.     closed, things would go very poorly. Another option would be to have a
  1308.     procedure, GetRearWindow, that would go through the window list and return
  1309.     the last window. Instead, we decided to present the standard approach
  1310.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  1311.     has a potential benefit in that the window whose document needs to be saved
  1312.     may be visible since it is the front window, therefore decreasing the
  1313.     chance of user confusion. For aesthetic reasons, the windows in the
  1314.     application should be checked for updates periodically and have the
  1315.     updates serviced.
  1316. **************************************************************************************/
  1317.  
  1318.  
  1319. /* Clean up the application and exit. We close all of the windows so that
  1320.  they can update their documents, if any. */
  1321.  
  1322. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  1323.     shell, but will return instead. */
  1324.  
  1325. #pragma segment Main
  1326. void Terminate()
  1327. {
  1328.     WindowPtr    aWindow;
  1329.     Boolean        closed;
  1330.     
  1331.     closed = true;
  1332.     do {
  1333.         aWindow = FrontWindow();                /* get the current front window */
  1334.         if (aWindow != nil)
  1335.             closed = DoCloseWindow(aWindow);    /* close this window */    
  1336.     }
  1337.     while (closed && (aWindow != nil));
  1338.     if (closed)
  1339.         ExitToShell();                            /* exit if no cancellation */
  1340. } /*Terminate*/
  1341.  
  1342.  
  1343. /*    Set up the whole world, including global variables, Toolbox managers,
  1344.     menus, and a single blank document. */
  1345.  
  1346. /*    1.01 - The code that used to be part of ForceEnvirons has been moved into
  1347.     this module. If an error is detected, instead of merely doing an ExitToShell,
  1348.     which leaves the user without much to go on, we call AlertUser, which puts
  1349.     up a simple alert that just says an error occurred and then calls ExitToShell.
  1350.     Since there is no other cleanup needed at this point if an error is detected,
  1351.     this form of error- handling is acceptable. If more sophisticated error recovery
  1352.     is needed, an exception mechanism, such as is provided by Signals, can be used. */
  1353.  
  1354. #pragma segment Initialize
  1355. void Initialize()
  1356. {
  1357.     Handle    menuBar;
  1358.     long    total, contig;
  1359.     EventRecord event;
  1360.     short    count;
  1361.  
  1362.     gInBackground = false;
  1363.  
  1364.     InitGraf((Ptr) &qd.thePort);
  1365.     InitFonts();
  1366.     InitWindows();
  1367.     InitMenus();
  1368.     TEInit();
  1369.     InitDialogs(nil);
  1370.     InitCursor();
  1371.  
  1372.     /*    Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  1373.          if you are using it. */
  1374.     /*    NOTE -- It is no longer necessary, and actually unhealthy, to check
  1375.         PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  1376.         of checking for port availability themselves. */
  1377.     
  1378.     /*    This next bit of code is necessary to allow the default button of our
  1379.         alert be outlined.
  1380.         1.02 - Changed to call EventAvail so that we don't lose some important
  1381.         events. */
  1382.      
  1383.     for (count = 1; count <= 3; count++)
  1384.         EventAvail(everyEvent, &event);
  1385.     
  1386.     /*    Ignore the error returned from SysEnvirons; even if an error occurred,
  1387.         the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  1388.         call to SysEnvirons by calling it after initializing AppleTalk. */
  1389.      
  1390.     SysEnvirons(kSysEnvironsVersion, &gMac);
  1391.     
  1392.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  1393.     
  1394.     if (gMac.machineType < 0) BigBadError(eWrongMachine);
  1395.     
  1396.     /*    1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  1397.         in TrapAvailable if a tool trap value is out of range. */
  1398.         
  1399.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
  1400.  
  1401.     /*    1.01 - We used to make a check for memory at this point by examining ApplLimit,
  1402.         ApplicZone, and StackSpace and comparing that to the minimum size we told
  1403.         MultiFinder we needed. This did not work well because it assumed too much about
  1404.         the relationship between what we asked MultiFinder for and what we would actually
  1405.         get back, as well as how to measure it. Instead, we will use an alternate
  1406.         method comprised of two steps. */
  1407.      
  1408.     /*    It is better to first check the size of the application heap against a value
  1409.         that you have determined is the smallest heap the application can reasonably
  1410.         work in. This number should be derived by examining the size of the heap that
  1411.         is actually provided by MultiFinder when the minimum size requested is used.
  1412.         The derivation of the minimum size requested from MultiFinder is described
  1413.         in Sample.h. The check should be made because the preferred size can end up
  1414.         being set smaller than the minimum size by the user. This extra check acts to
  1415.         insure that your application is starting from a solid memory foundation. */
  1416.      
  1417.     if ((long) GetApplLimit() - (long) ApplicZone() < kMinHeap) BigBadError(eSmallSize);
  1418.     
  1419.     /*    Next, make sure that enough memory is free for your application to run. It
  1420.         is possible for a situation to arise where the heap may have been of required
  1421.         size, but a large scrap was loaded which left too little memory. To check for
  1422.         this, call PurgeSpace and compare the result with a value that you have determined
  1423.         is the minimum amount of free memory your application needs at initialization.
  1424.         This number can be derived several different ways. One way that is fairly
  1425.         straightforward is to run the application in the minimum size configuration
  1426.         as described previously. Call PurgeSpace at initialization and examine the value
  1427.         returned. However, you should make sure that this result is not being modified
  1428.         by the scrap's presence. You can do that by calling ZeroScrap before calling
  1429.         PurgeSpace. Make sure to remove that call before shipping, though. */
  1430.     
  1431.     /* ZeroScrap(); */
  1432.  
  1433.     PurgeSpace(&total, &contig);
  1434.     if (total < kMinSpace)
  1435.         if (UnloadScrap() != noErr)
  1436.             BigBadError(eNoMemory);
  1437.         else {
  1438.             PurgeSpace(&total, &contig);
  1439.             if (total < kMinSpace)
  1440.                 BigBadError(eNoMemory);
  1441.         }
  1442.  
  1443.     /*    The extra benefit to waiting until after the Toolbox Managers have been initialized
  1444.         to check memory is that we can now give the user an alert to tell him/her what
  1445.         happened. Although it is possible that the memory situation could be worsened by
  1446.         displaying an alert, MultiFinder would gracefully exit the application with
  1447.         an informative alert if memory became critical. Here we are acting more
  1448.         in a preventative manner to avoid future disaster from low-memory problems. */
  1449.  
  1450.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  1451.     if ( menuBar == nil )
  1452.                 BigBadError(eNoMemory);
  1453.     SetMenuBar(menuBar);                    /* install menus */
  1454.     DisposHandle(menuBar);
  1455.     AddResMenu(GetMHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  1456.     DrawMenuBar();
  1457.  
  1458.     gNumDocuments = 0;
  1459.  
  1460.     /* do other initialization here */
  1461.  
  1462.     DoNew();                                /* create a single empty document */
  1463. } /*Initialize*/
  1464.  
  1465.  
  1466. /* Used whenever a, like, fully fatal error happens */
  1467. #pragma segment Initialize
  1468. void BigBadError(error)
  1469.     short error;
  1470. {
  1471.     AlertUser(error);
  1472.     ExitToShell();
  1473. }
  1474.  
  1475.  
  1476. /* Return a rectangle that is inset from the portRect by the size of
  1477.     the scrollbars and a little extra margin. */
  1478.  
  1479. #pragma segment Main
  1480. void GetTERect(window,teRect)
  1481.     WindowPtr    window;
  1482.     Rect        *teRect;
  1483. {
  1484.     *teRect = window->portRect;
  1485.     InsetRect(teRect, kTextMargin, kTextMargin);    /* adjust for margin */
  1486.     teRect->bottom = teRect->bottom - 15;        /* and for the scrollbars */
  1487.     teRect->right = teRect->right - 15;
  1488. } /*GetTERect*/
  1489.  
  1490.  
  1491. /* Update the TERec's view rect so that it is the greatest multiple of
  1492.     the lineHeight that still fits in the old viewRect. */
  1493.  
  1494. #pragma segment Main
  1495. void AdjustViewRect(docTE)
  1496.     TEHandle    docTE;
  1497. {
  1498.     TEPtr        te;
  1499.     
  1500.     te = *docTE;
  1501.     te->viewRect.bottom = (((te->viewRect.bottom - te->viewRect.top) / te->lineHeight)
  1502.                             * te->lineHeight) + te->viewRect.top;
  1503. } /*AdjustViewRect*/
  1504.  
  1505.  
  1506. /* Scroll the TERec around to match up to the potentially updated scrollbar
  1507.     values. This is really useful when the window has been resized such that the
  1508.     scrollbars became inactive but the TERec was already scrolled. */
  1509.  
  1510. #pragma segment Main
  1511. void AdjustTE(window)
  1512.     WindowPtr    window;
  1513. {
  1514.     TEPtr        te;
  1515.     
  1516.     te = *((DocumentPeek)window)->docTE;
  1517.     TEScroll((te->viewRect.left - te->destRect.left) -
  1518.             GetCtlValue(((DocumentPeek)window)->docHScroll),
  1519.             (te->viewRect.top - te->destRect.top) -
  1520.                 (GetCtlValue(((DocumentPeek)window)->docVScroll) *
  1521.                 te->lineHeight),
  1522.             ((DocumentPeek)window)->docTE);
  1523. } /*AdjustTE*/
  1524.  
  1525.  
  1526. /* Calculate the new control maximum value and current value, whether it is the horizontal or
  1527.     vertical scrollbar. The vertical max is calculated by comparing the number of lines to the
  1528.     vertical size of the viewRect. The horizontal max is calculated by comparing the maximum document
  1529.     width to the width of the viewRect. The current values are set by comparing the offset between
  1530.     the view and destination rects. If necessary and we canRedraw, have the control be re-drawn by
  1531.     calling ShowControl. */
  1532.  
  1533. #pragma segment Main
  1534. void AdjustHV(isVert,control,docTE,canRedraw)
  1535.     Boolean        isVert;
  1536.     ControlHandle control;
  1537.     TEHandle    docTE;
  1538.     Boolean        canRedraw;
  1539. {
  1540.     short        value, lines, max;
  1541.     short        oldValue, oldMax;
  1542.     TEPtr        te;
  1543.     
  1544.     oldValue = GetCtlValue(control);
  1545.     oldMax = GetCtlMax(control);
  1546.     te = *docTE;                            /* point to TERec for convenience */
  1547.     if ( isVert ) {
  1548.         lines = te->nLines;
  1549.         /* since nLines isn’t right if the last character is a return, check for that case */
  1550.         if ( *(*te->hText + te->teLength - 1) == kCrChar )
  1551.             lines += 1;
  1552.         max = lines - ((te->viewRect.bottom - te->viewRect.top) /
  1553.                 te->lineHeight);
  1554.     } else
  1555.         max = kMaxDocWidth - (te->viewRect.right - te->viewRect.left);
  1556.     
  1557.     if ( max < 0 ) max = 0;
  1558.     SetCtlMax(control, max);
  1559.     
  1560.     /* Must deref. after SetCtlMax since, technically, it could draw and therefore move
  1561.         memory. This is why we don’t just do it once at the beginning. */
  1562.     te = *docTE;
  1563.     if ( isVert )
  1564.         value = (te->viewRect.top - te->destRect.top) / te->lineHeight;
  1565.     else
  1566.         value = te->viewRect.left - te->destRect.left;
  1567.     
  1568.     if ( value < 0 ) value = 0;
  1569.     else if ( value >  max ) value = max;
  1570.     
  1571.     SetCtlValue(control, value);
  1572.     /* now redraw the control if it needs to be and can be */
  1573.     if ( canRedraw || (max != oldMax) || (value != oldValue) )
  1574.         ShowControl(control);
  1575. } /*AdjustHV*/
  1576.  
  1577.  
  1578. /* Simply call the common adjust routine for the vertical and horizontal scrollbars. */
  1579.  
  1580. #pragma segment Main
  1581. void AdjustScrollValues(window,canRedraw)
  1582.     WindowPtr    window;
  1583.     Boolean        canRedraw;
  1584. {
  1585.     DocumentPeek doc;
  1586.     
  1587.     doc = (DocumentPeek)window;
  1588.     AdjustHV(true, doc->docVScroll, doc->docTE, canRedraw);
  1589.     AdjustHV(false, doc->docHScroll, doc->docTE, canRedraw);
  1590. } /*AdjustScrollValues*/
  1591.  
  1592.  
  1593. /*    Re-calculate the position and size of the viewRect and the scrollbars.
  1594.     kScrollTweek compensates for off-by-one requirements of the scrollbars
  1595.     to have borders coincide with the growbox. */
  1596.  
  1597. #pragma segment Main
  1598. void AdjustScrollSizes(window)
  1599.     WindowPtr    window;
  1600. {
  1601.     Rect        teRect;
  1602.     DocumentPeek doc;
  1603.     
  1604.     doc = (DocumentPeek) window;
  1605.     GetTERect(window, &teRect);                            /* start with TERect */
  1606.     (*doc->docTE)->viewRect = teRect;
  1607.     AdjustViewRect(doc->docTE);                            /* snap to nearest line */
  1608.     MoveControl(doc->docVScroll, window->portRect.right - kScrollbarAdjust, -1);
  1609.     SizeControl(doc->docVScroll, kScrollbarWidth, (window->portRect.bottom - 
  1610.                 window->portRect.top) - (kScrollbarAdjust - kScrollTweek));
  1611.     MoveControl(doc->docHScroll, -1, window->portRect.bottom - kScrollbarAdjust);
  1612.     SizeControl(doc->docHScroll, (window->portRect.right - 
  1613.                 window->portRect.left) - (kScrollbarAdjust - kScrollTweek),
  1614.                 kScrollbarWidth);
  1615. } /*AdjustScrollSizes*/
  1616.  
  1617.  
  1618. /* Turn off the controls by jamming a zero into their contrlVis fields (HideControl erases them
  1619.     and we don't want that). If the controls are to be resized as well, call the procedure to do that,
  1620.     then call the procedure to adjust the maximum and current values. Finally re-enable the controls
  1621.     by jamming a $FF in their contrlVis fields. */
  1622.  
  1623. #pragma segment Main
  1624. void AdjustScrollbars(window,needsResize)
  1625.     WindowPtr    window;
  1626.     Boolean        needsResize;
  1627. {
  1628.     DocumentPeek doc;
  1629.     
  1630.     doc = (DocumentPeek) window;
  1631.     /* First, turn visibility of scrollbars off so we won’t get unwanted redrawing */
  1632.     (*doc->docVScroll)->contrlVis = kControlInvisible;    /* turn them off */
  1633.     (*doc->docHScroll)->contrlVis = kControlInvisible;
  1634.     if ( needsResize )                                    /* move & size as needed */
  1635.         AdjustScrollSizes(window);
  1636.     AdjustScrollValues(window, needsResize);            /* fool with max and current value */
  1637.     /* Now, restore visibility in case we never had to ShowControl during adjustment */
  1638.     (*doc->docVScroll)->contrlVis = kControlVisible;    /* turn them on */
  1639.     (*doc->docHScroll)->contrlVis = kControlVisible;
  1640. } /* AdjustScrollbars */
  1641.  
  1642.  
  1643. /* Gets called from our assembly language routine, AsmClikLoop, which is in
  1644.     turn called by the TEClick toolbox routine. Saves the windows clip region,
  1645.     sets it to the portRect, adjusts the scrollbar values to match the TE scroll
  1646.     amount, then restores the clip region. */
  1647.  
  1648. #pragma segment Main
  1649. pascal  void PascalClikLoop()
  1650. {
  1651.     WindowPtr    window;
  1652.     RgnHandle    region;
  1653.     
  1654.     window = FrontWindow();
  1655.     region = NewRgn();
  1656.     GetClip(region);                    /* save clip */
  1657.     ClipRect(&window->portRect);
  1658.     AdjustScrollValues(window, true);    /* pass true for canRedraw */
  1659.     SetClip(region);                    /* restore clip */
  1660.     DisposeRgn(region);
  1661. } /* Pascal/C ClikLoop */
  1662.  
  1663.  
  1664. /* Gets called from our assembly language routine, AsmClikLoop, which is in
  1665.     turn called by the TEClick toolbox routine. It returns the address of the
  1666.     default clikLoop routine that was put into the TERec by TEAutoView to
  1667.     AsmClikLoop so that it can call it. */
  1668.  
  1669. #pragma segment Main
  1670. pascal ProcPtr GetOldClikLoop()
  1671. {
  1672.     return ((DocumentPeek)FrontWindow())->docClik;
  1673. } /* GetOldClikLoop */
  1674.  
  1675.  
  1676. /*    Check to see if a window belongs to the application. If the window pointer
  1677.     passed was NIL, then it could not be an application window. WindowKinds
  1678.     that are negative belong to the system and windowKinds less than userKind
  1679.     are reserved by Apple except for windowKinds equal to dialogKind, which
  1680.     mean it is a dialog.
  1681.     1.02 - In order to reduce the chance of accidentally treating some window
  1682.     as an AppWindow that shouldn't be, we'll only return true if the windowkind
  1683.     is userKind. If you add different kinds of windows to Sample you'll need
  1684.     to change how this all works. */
  1685.  
  1686. #pragma segment Main
  1687. Boolean IsAppWindow(window)
  1688.     WindowPtr    window;
  1689. {
  1690.     short        windowKind;
  1691.  
  1692.     if ( window == nil )
  1693.         return false;
  1694.     else {    /* application windows have windowKinds = userKind (8) */
  1695.         windowKind = ((WindowPeek) window)->windowKind;
  1696.         return (windowKind == userKind);
  1697.     }
  1698. } /*IsAppWindow*/
  1699.  
  1700.  
  1701. /* Check to see if a window belongs to a desk accessory. */
  1702.  
  1703. #pragma segment Main
  1704. Boolean IsDAWindow(window)
  1705.     WindowPtr    window;
  1706. {
  1707.     if ( window == nil )
  1708.         return false;
  1709.     else    /* DA windows have negative windowKinds */
  1710.         return ((WindowPeek) window)->windowKind < 0;
  1711. } /*IsDAWindow*/
  1712.  
  1713.  
  1714. /*    Check to see if a given trap is implemented. This is only used by the
  1715.     Initialize routine in this program, so we put it in the Initialize segment.
  1716.     The recommended approach to see if a trap is implemented is to see if
  1717.     the address of the trap routine is the same as the address of the
  1718.     Unimplemented trap. */
  1719. /*    1.02 - Needs to be called after call to SysEnvirons so that it can check
  1720.     if a ToolTrap is out of range of a pre-MacII ROM. */
  1721.  
  1722. #pragma segment Initialize
  1723. Boolean TrapAvailable(tNumber,tType)
  1724.     short        tNumber;
  1725.     TrapType    tType;
  1726. {
  1727.     if ( ( tType == (unsigned char) ToolTrap ) &&
  1728.         ( gMac.machineType > envMachUnknown ) &&
  1729.         ( gMac.machineType < envMacII ) ) {        /* it's a 512KE, Plus, or SE */
  1730.         tNumber = tNumber & 0x03FF;
  1731.         if ( tNumber > 0x01FF )                    /* which means the tool traps */
  1732.             tNumber = _Unimplemented;            /* only go to 0x01FF */
  1733.     }
  1734.     return NGetTrapAddress(tNumber, tType) != GetTrapAddress(_Unimplemented);
  1735. } /*TrapAvailable*/
  1736.  
  1737.  
  1738. /*    Display an alert that tells the user an error occurred, then exit the program.
  1739.     This routine is used as an ultimate bail-out for serious errors that prohibit
  1740.     the continuation of the application. Errors that do not require the termination
  1741.     of the application should be handled in a different manner. Error checking and
  1742.     reporting has a place even in the simplest application. The error number is used
  1743.     to index an 'STR#' resource so that a relevant message can be displayed. */
  1744.  
  1745. #pragma segment Main
  1746. void AlertUser(error)
  1747.     short        error;
  1748. {
  1749.     short        itemHit;
  1750.     Str255        message;
  1751.  
  1752.     SetCursor(&qd.arrow);
  1753.     /* type Str255 is an array in MPW 3 */
  1754.     GetIndString(message, kErrStrings, error);
  1755.     ParamText(message, "", "", "");
  1756.     itemHit = Alert(rUserAlert, nil);
  1757. } /* AlertUser */
  1758.